<template>
	<view class="modal" @click="$emit('close', {isCreate: false})">
		<view class="modal-content" @click.stop>
			<view class="modal-header">
				<view class="modal-handle"></view>
			</view>
			<view class="form-group">
				<!-- 第一组第一行计划提醒方式 -->
				<view class="form-row">
					<view v-for="(item, index) in remindWayDesc" :key="index" class="custom-radio"
						:class="{ selected: remindWay === item.id }" @click.stop="remindWay = item.id">
						{{ item.name }}
					</view>
				</view>
				<!-- 第一组第二行计划提醒时间 -->
				<view class="form-row">
					<view v-for="(item, index) in remindBeforeSecondDesc" :key="index" class="custom-radio"
						:class="{ selected: remindBeforeSecond === item.second }"
						@click.stop="remindSecondHandle(item)">
						{{ item.name }}
					</view>
				</view>
				<!-- 第一组第三行计划重要性 -->
				<view class="form-row">
					<view v-for="(item, index) in priorityDesc" :key="index" class="custom-radio"
						:class="{ selected: priority === item.id }" @click.stop="priority = item.id">
						{{ item.name }}
					</view>
				</view>
				<!-- 第一组第四行：计划类型 -->
				<view class="form-row">
					<view v-for="(item, index) in planTypeDesc" :key="index" class="custom-radio"
						:class="{ selected: planType === item.id }" @click.stop="planType = item.id">
						{{ item.name }}
					</view>
				</view>
			</view>

			<view class="form-group">
				<!-- 第二组第一行是否重复 -->
				<view class="form-row">
					<view class="custom-radio" :class="{ selected: loopAuto === false}" @click.stop="closeLoopModal">
						仅一次
					</view>
					<view class="custom-radio" :class="{ selected: loopAuto === true }" @click.stop="showLoopModal">
						重复
					</view>
				</view>

				<!-- 第二组第二行：时间选择 -->
				<!-- @change="handleStartTimeChange" -->
				<view class="form-row">
					<picker mode="time" class="custom-picker" start="startTime" :value="startTime"
						@change="handleStartTimeChange">
						<view class="picker-view">{{ startTime || '选择开始时间' }}</view>
					</picker>
					<view class="separator">一</view>
					<picker mode="time" format="HH:mm:ss" class="custom-picker" :value="endTime"
						@change="handleEndTimeChange">
						<view class="picker-view">{{ endTime || '选择结束时间' }}</view>
					</picker>
				</view>
			</view>

			<view class="form-group">
				<!-- 第三组第一行：计划名称，限制8个字符 -->
				<view class="form-row">
					<template class="char-container">
						<input type="text" class="input-field" maxlength="8" v-model="planName" placeholder="计划名称" />
						<!-- <view class="char-count">{{ planName.length }}/{{ maxPlanNameLength }}</view> -->
					</template>
				</view>

				<!-- 第三组第二行：内容，限制500字符 -->
				<view class="form-row">
					<template class="char-container">
						<input type="text" class="input-field" maxlength="500" v-model="planDetail"
							placeholder="计划内容" />
						<!-- <textarea maxlength="500" v-model="planDetail" class="textarea-field"
							placeholder="请输入内容"></textarea>
						<view class="char-count">{{ planDetail.length }}/{{ maxPlanDetailLength }}</view> -->
					</template>
				</view>
			</view>

			<view class="button-row">
				<button type="primary" class="default-btn cancel"
					@click.stop="$emit('close', {isCreate: false})">取消</button>
				<button type="primary" class="default-btn confirm" @click.stop="submitForm">确定</button>
			</view>
		</view>
		<!-- 重复悬浮窗 -->
		<view v-if="modalVisible" class="overlay" @click.stop="closeModal">
			<view class="floating-modal">
				<view class="form-group">
					<view class="form-item" :class="{ selected: selectedOption === 'daily' }"
						@click.stop="selectOption('daily')">
						每天</view>
					<view class="form-item" :class="{ selected: selectedOption === 'weekly' }"
						@click.stop="selectOption('weekly')">周一到周五</view>
					<view class="form-item" :class="{ selected: selectedOption === 'custom' }"
						@click.stop="showCustomModal">
						自定义
					</view>
				</view>
				<view class="button-row">
					<button type="primary" class="default-btn cancel" @click.stop="backToBaseModal">上一步</button>
					<button type="primary" class="default-btn confirm" @click.stop="confirmCustomSelection">确定</button>
				</view>
			</view>
		</view>

		<!-- 自定义悬浮窗 -->
		<view v-if="customModalVisible" class="overlay">
			<view class="floating-modal">
				<view class="form-group">
					<view class="form-item" v-for="day in weekDays" :key="day"
						:class="{ selected: selectedDays.includes(day) }" @click.stop="toggleDaySelection(day)">
						{{ day }}
					</view>
				</view>
				<view class="button-row">
					<button type="primary" class="default-btn cancel" @click.stop="backToFirstModal">上一步</button>
					<button type="primary" class="default-btn confirm" @click.stop="confirmCustomSelection">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		inject
	} from 'vue';
	import {
		defineProps,
		defineEmits
	} from 'vue';
	import {
		apiQueryPlan,
		apiCreatePlan,
		apiUpdatePlan
	} from "@/requestApi/plan.js";
	import {
		checkCalendar,
		addCalendar,
	} from "@/utils/calendar";
	const formatScheduleJson = inject("formatScheduleJson")
	const emit = defineEmits(['close']);
	const props = defineProps(['planFormData'])
	console.log(props)
	const planFormData = ref(props.planFormData);
	const loopAuto = ref(planFormData.value.loopAuto);
	const loopType = ref(planFormData.value.loopType);
	const loopCustom = ref(planFormData.value.loopCustom); //自定义重复:loopType为6才传, 1-7表示周一到周日,比如一三五就传1,3,5
	const startTime = ref(planFormData.value.startTime);
	// const startTime = ref("09:00");
	const endTime = ref(planFormData.value.endTime);
	const planName = ref(planFormData.value.name);
	const planDetail = ref(planFormData.value.planDetail);
	const planType = ref(planFormData.value.planType);
	const planTypeDesc = ref([{
			id: 1,
			name: '工作'
		},
		{
			id: 2,
			name: '社交'
		},
		{
			id: 3,
			name: '个人'
		}
	]);
	const priority = ref(1); // 计划重要性
	const priorityDesc = ref([{
			id: 3,
			name: '非常重要'
		},
		{
			id: 2,
			name: '重要'
		},
		{
			id: 1,
			name: '一般'
		}
	]);
	const remindAuto = ref(planFormData.value.remindAuto); // 是否开启提醒:
	const remindBeforeSecond = ref(planFormData.value.remindBeforeSecond); // 计划提醒时间 提前多少秒提醒:remindAuto为true才传
	const remindBeforeSecondDesc = ref([{
			id: 1,
			second: 600,
			name: '前10分钟'
		},
		{
			id: 2,
			second: 0,
			name: '到点提醒'
		},
		{
			id: 3,
			second: -1,
			name: '不提醒'
		}
	]);
	const remindWay = ref(planFormData.value.remindWay); // 提醒方式:remindAuto为true才传, 1AI电话/2应用提醒
	const remindWayDesc = ref([{
			id: 1,
			name: 'AI提醒'
		},
		{
			id: 2,
			name: '应用提醒'
		}
	]);
	const endDate = ref(planFormData.value.endDate); // endDate
	const maxPlanNameLength = 8;
	const maxPlanDetailLength = 500;
	const currentTextLength = computed(() => planName.value.length);

	const handleStartTimeChange = (e) => {
		console.log('eeeeee', e);
		e.stopPropagation();
		startTime.value = e.detail.value;
	};
	const handleEndTimeChange = (e) => {
		console.log('eee', e, e.detail.value);
		e.stopPropagation();
		endTime.value = e.detail.value;
	};
	const remindSecondHandle = (item) => {
		remindAuto.value = (item.second == -1);
		remindBeforeSecond.value = item.second;
	}

	const selectedDays = ref([]);
	const weekDays = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日']);
	const modalVisible = ref(false);
	const customModalVisible = ref(false);
	const selectedOption = ref(null);

	// 选择仅一次
	const closeLoopModal = () => {
		//option1.value = false;
		loopAuto.value = false;
	};


	// 打开重复弹窗
	const showLoopModal = () => {
		console.log('123', selectedOption.value)
		//option1.value = false;
		loopAuto.value = true
		modalVisible.value = true;
	};

	const closeModal = () => {
		console.log('333', selectedOption.value)
		if (!selectedOption.value || (selectedOption.value == 'custom' && selectedDays.value && !selectedDays.value
				.length > 0)) {
			loopAuto.value = false;
			selectedOption.value = null;
		}
		modalVisible.value = false;
		//selectedOption.value = null;
	};

	const selectOption = (option) => {
		console.log('222', option)
		if (option && option !== 'custom') {
			selectedDays.value = [];
		}
		closeModal.value = false;
		selectedOption.value = option;
	};

	const showCustomModal = () => {
		selectedOption.value = 'custom';
		modalVisible.value = false;
		customModalVisible.value = true;
	};

	const backToBaseModal = () => {
		// 1.判断是否有值
		// 2. 当值为customer时, 判断 selectedDays.value 是否有值

		if (!selectedOption.value || (selectedOption.value == 'custom' && selectedDays.value && !selectedDays.value
				.length > 0)) {
			loopAuto.value = false;
			selectedOption.value = null;
		}
		customModalVisible.value = false;
		modalVisible.value = false;

	};

	const backToFirstModal = () => {
		customModalVisible.value = false;
		modalVisible.value = true;
		// selectedOption.value = null;
	};

	const closeCustomModal = () => {
		customModalVisible.value = false;
		selectedDays.value = [];
	};

	const confirmCustomSelection = () => {
		console.log();
		if (!selectedOption.value || (selectedOption.value == 'custom' && selectedDays.value && !selectedDays.value
				.length > 0)) {
			loopAuto.value = false;
			selectedOption.value = null;
		}
		modalVisible.value = false;
		customModalVisible.value = false;
		// 处理自定义选项选择后的逻辑
	};

	const toggleDaySelection = (day) => {
		if (selectedDays.value.includes(day)) {
			selectedDays.value = selectedDays.value.filter(d => d !== day);
		} else {
			selectedDays.value.push(day);
		}
	};

	const submitForm = () => {
		// 处理提交逻辑
		console.log({
			id: planFormData.value.id,
			loopAuto: loopAuto.value,
			loopType: loopType.value,
			loopCustom: loopCustom.value,
			startTime: `${planFormData.value.startDate} ${startTime.value}:00`,
			endTime: `${planFormData.value.startDate} ${endTime.value}:00`,
			planName: planName.value,
			planDetail: planDetail.value,
			planType: planType.value,
			endDate: endDate.value
		});
		let data = {
			planId: planFormData.value.id,
			name: planName.value,
			planDetail: planDetail.value,
			planType: planType.value,
			priority: priority.value,
			loopAuto: loopAuto.value,
			remindAuto: remindAuto.value,
			startDate: `${planFormData.value.startDate}T00:00:00`,
			//endDate:  `${checkDate.value}T${startTime.value}:00`,
			startTime: `${planFormData.value.startDate}T${startTime.value}:00`,
			endTime: `${planFormData.value.startDate}T${endTime.value}:00`
		}
		if (loopAuto.value) {
			data.loopType = loopType.value;
			if (loopType.value === 6) {
				data.loopCustom = loopCustom.value;
			}
		}
		if (remindAuto.value) {
			data.remindWay = remindWay.value;
			data.remindBeforeSecond = remindBeforeSecond.value;
		}

		if (planFormData.value.id) {
			const currentDateTime = new Date();
			const currentDate = currentDateTime.toISOString().split('T')[0];
			data.operatorDate = currentDate;
			// 编辑
			apiUpdatePlan(data).then(res => {
				console.log(res, 'res')
				if (res.code == 1) {
					let scheduleJson = formatScheduleJson(data, res.data.recordId)
					console.log(scheduleJson, 'scheduleJson')
					addCalendar(scheduleJson)
					uni.showModal({
						title: '更新完成',
						content: '计划编辑成功!',
						showCancel: false,
						confirmText: '好的'
					});
					emit('close', {
						isCreate: true
					});
				} else {
					emit('close', {
						isCreate: false
					});
				}
			}).catch(err => {
				console.log(err, 'err')
			})
		} else {
			// 新建
			apiCreatePlan(data).then(res => {
				console.log(res, 'res')
				if (res.code == 1) {
					let scheduleJson = formatScheduleJson(data, res.data.recordId)
					console.log(scheduleJson, 'scheduleJson')
					addCalendar(scheduleJson)
					uni.showModal({
						title: '创建完成',
						content: '计划创建成功!',
						showCancel: false,
						confirmText: '好的'
					});
					emit('close', {
						isCreate: true
					});

				} else {
					emit('close', {
						isCreate: false
					});
				}
			}).catch(err => {
				console.log(err, 'err')
			})
		}
	};
</script>

<style scoped lang="less">
	* {
		font-size: 16px;
		text-align: center;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		//justify-content: center;
		align-items: flex-end;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.modal-header {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 50rpx;
	}

	.modal-handle {
		width: 40px;
		height: 4px;
		background-color: #ccc;
		border-radius: 2px;
	}

	.modal-content {
		width: 100%;
		height: 80vh;
		//max-width: 400px;
		background-color: #fff;
		padding: 15px 0 0 0;
		border-radius: 10px 10px 0 0;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
	}

	.form-group {
		width: 80vw;
		border: 1rpx solid #ADB5BD;
		border-radius: 20rpx;
		padding: 0 30rpx;
		margin-bottom: 66rpx;
	}


	.form-row {
		width: 100%;
		display: flex;
		margin: 0;
		border-bottom: 1rpx solid #ADB5BD;
	}

	.form-row:last-child {
		border-bottom: none;
	}

	.form-item {
		color: #ADB5BD;
		padding: 24rpx 0;
		border-bottom: 1rpx solid #ADB5BD;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.custom-picker {
		flex: 1;
	}

	.picker-view {
		text-align: center;
		padding: 24rpx 0;
		background-color: #fff;
		color: #000;
		border-radius: 5px;
	}

	.separator {
		width: 30px;
		text-align: center;
		color: #000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.custom-radio {
		flex: 1;
		color: #ADB5BD;
		display: inline-block;
		padding: 24rpx 0;
	}

	.custom-radio.selected,
	.form-row.selected,
	.form-item.selected {
		// background-color: #FACD91;
		color: #000;
	}

	.char-container {
		position: relative;
		display: flex;
		align-items: center;
		border-radius: 4px;
		padding: 4px;
		width: 100%;
	}

	input[type="text"] {
		flex: 1;
		padding: 8px;
		font-size: 16px;
	}

	.input-field {
		flex: 1;
		padding: 10px;
		border-radius: 5px;
		margin-right: 10px;
	}

	.textarea-field {
		flex: 1;
		padding: 10px;
		border-radius: 5px;
		margin-right: 10px;
		resize: none;
		height: 100px;
		box-sizing: border-box;
	}

	.textarea-field::placeholder {
		display: flex;
		align-items: center;
		height: 100%;
		line-height: 100px;
		vertical-align: middle;
	}

	.textarea-field .uni-textarea-placeholder {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.char-count {
		position: absolute;
		right: 5px;
		bottom: 0;
		white-space: nowrap;
		//margin-left: 10px;
		color: #999;
		font-size: 14px;
	}

	.button-row {
		width: 80vw;
		padding: 0 30rpx;
		position: relative;
		justify-content: space-between;
	}

	.default-btn {
		width: 40vw;
		height: 70rpx;
	}

	button.cancel {
		position: absolute;
		left: 0;
		background-color: #F49F9D;
		color: white;
	}

	button.confirm {
		position: absolute;
		right: 0;
		background-color: #000;
		color: white;
	}

	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: flex-end;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.floating-modal {
		width: 100%;
		height: 80vh;
		//max-width: 400px;
		background-color: #fff;
		padding: 15px 0 0 0;
		border-radius: 10px 10px 0 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
</style>